/**
 * 
 */
package com.ph.shopping.facade.agent.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ph.shopping.common.core.base.BaseService;
import com.ph.shopping.common.core.constant.CommonConstants;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.core.customenum.RoleEnum;
import com.ph.shopping.common.core.customenum.SmsCodeType;
import com.ph.shopping.common.core.exception.BizException;
import com.ph.shopping.common.util.page.PageBean;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.common.util.rsa.MD5;
import com.ph.shopping.facade.agent.entity.Agent;
import com.ph.shopping.facade.agent.entity.AgentChargeRecord;
import com.ph.shopping.facade.agent.entity.AgentDrawcashRecord;
import com.ph.shopping.facade.agent.entity.AgentImage;
import com.ph.shopping.facade.agent.service.IAgentService;
import com.ph.shopping.facade.agent.vo.AgentVo;
import com.ph.shopping.facade.agent.vo.UserBalanceRecordVo;
import com.ph.shopping.facade.mapper.*;
import com.ph.shopping.facade.member.service.ISmsCodeSendService;
import com.ph.shopping.facade.merchant.entity.Merchant;
import com.ph.shopping.facade.merchant.entity.Position;
import com.ph.shopping.facade.merchant.service.IMerchantService;
import com.ph.shopping.facade.merchant.vo.MerchantDetaileVo;
import com.ph.shopping.facade.permission.dto.UserRoleDto;
import com.ph.shopping.facade.permission.entity.User;
import com.ph.shopping.facade.permission.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @项目：phshopping-service-agent
 *
 * @描述：
 *
 * @作者： 舒豪
 *
 * @创建时间：2017年3月10日
 *
 * @Copyright @2017 by 舒豪
 */
@Component
@Service(version="1.0.0")
public class AgentService  extends BaseService implements IAgentService {

    @Autowired
    private AgentMapper agentMapper;
    @Autowired
    private AgentImageMapper agentImageMapper;
    @Autowired
    private AgentMerchantMapper merchantMapper;

	//代理商充值记录
	@Autowired
	private AgentChargeRecordMapper agentChargeRecordMapper;

	//代理商提现记录
	@Autowired
	private AgentDrawcashRecordMapper agentDrawcashRecordMapper;

    @Reference(version = "1.0.0")
    private IUserService iUserService;

	//发送短信接口
    @Reference(version = "1.0.0")
    private ISmsCodeSendService smsCodeSendService;

    @Reference(version = "1.0.0")
    private IMerchantService iMerchantService;

	/**
	 * 生成随机密码
	 * 
	 * @return
	 */
	public static String getSmsCode() {
		return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
	}
	
    public AgentVo getAgentDetail(Agent agent) {

        AgentVo agentVo =agentMapper.getAgentDetail(agent);
        //获取商户图片
        AgentImage a1=new AgentImage();
        a1.setAgentId(agent.getId());
        //获取身份证图片
        a1.setType(2);
        List<AgentImage> a1s=agentImageMapper.getAgentImageById(a1);
        //获取营业执照图片
        a1.setType(1);
        List<AgentImage> a2s=agentImageMapper.getAgentImageById(a1);
        agentVo.setBusinessImage(a2s);
        agentVo.setIdCardsImage(a1s);
        return agentVo;
    }

    public Result getAgentSons(PageBean page, Agent agent) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<AgentVo> list = (Page<AgentVo>) agentMapper.getAgentSons(agent);
        PageInfo<AgentVo> pageInfo = new PageInfo<AgentVo>(list);
        return getResult(ResultEnum.SUCCESS, pageInfo.getList(), pageInfo.getTotal());
    }

    public Result getPendingAgent(PageBean page, Agent agent) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<AgentVo> list = new ArrayList<AgentVo>();
        if (agent.getAgentLevelId() == 5) {
            //获取待审核的县级代理
            agent.setAgentLevelId(new Long(2));
            List<AgentVo> listCounty = agentMapper.getPendingAgent(agent);
            //获取待审核的社区代理
            agent.setAgentLevelId(new Long(3));
            List<AgentVo> listTown = agentMapper.getPendingAgent(agent);

            list.addAll(listCounty);
            list.addAll(listTown);
        } else {
            list = agentMapper.getPendingAgent(agent);
        }

        PageInfo<AgentVo> pageInfo = new PageInfo<AgentVo>(list);
        return getResult(ResultEnum.SUCCESS, pageInfo.getList(), pageInfo.getTotal());
    }


    public Result getAgentList(PageBean page, Agent agent) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<AgentVo> list = agentMapper.getAgentList(agent);
        PageInfo<AgentVo> pageInfo = new PageInfo<AgentVo>(list);
        return getResult(ResultEnum.SUCCESS, pageInfo.getList(), pageInfo.getTotal());
    }

    @Transactional(rollbackFor=Exception.class)
    public Result addAgent(Agent agent, List<AgentImage> imageList)  throws BizException{

        //设置PositionId的值
        setPositionId(agent);

        //区域转换
        agent = transArea(agent);

    	Long deleteUserId = 0l;//用于代理商新增失败时，回滚用户新增的操作
        Result result = getResult(ResultEnum.SUCCESS);
        try {
            logger.info("代理商新增");
            logger.debug("agent: " + new ObjectMapper().writeValueAsString(agent));
            logger.debug("imageList: " + new ObjectMapper().writeValueAsString(imageList));

            //检查该区域该级别代理商是否存在
            long levelId=agent.getAgentLevelId();

            //如果是市级代理去掉区
            long countyId = agent.getCountyId();
            if (1 == levelId) {
                agent.setCountyId(null);
            }

            AgentVo agentVo = agentMapper.getAgentByArea(agent);
            if(agentVo!=null){
                if (agentVo.getAgentLevelId() == 3) {
                    return getResult(ResultEnum.ENTITY_COMMUNITY_HAVE_EXCEPTION);
                } else {
                    return getResult(ResultEnum.ENTITY_AGENT_HAVE_EXCEPTION);
                }
            }
            //还原
            agent.setCountyId(countyId);


            //1.新增一个用户,返回id
            UserRoleDto dto = new UserRoleDto();
            dto.setTelphone(agent.getPersonTel());
            //设置代理级别
            long LevelId=agent.getAgentLevelId();
            if(1==LevelId){
                dto.setRoleCode(RoleEnum.CITY_AGENT.getCode());//设置为市级代理
            }else if(2==LevelId){
                dto.setRoleCode(RoleEnum.COUNTY_AGENT.getCode());//设置为县级代理
            }else if(3==LevelId){
                dto.setRoleCode(RoleEnum.COMMUNITY_AGENT.getCode());//设置为社区代理
            }
            Result userResult = iUserService.addUser(dto);//新增用户,调用用户接口

            //调用用户接口后，判断1.result是否为空;2.返回的Code是否为“用户已注册”;3.判断是否返回成功Code
            if (null != userResult && !ResultEnum.REGISTERED.getCode().equals(userResult.getCode())
                    && ResultEnum.SUCCESS.getCode().equals(userResult.getCode())) {

                Long userId = (Long) userResult.getData();//返回的Id
		        deleteUserId = userId;//用于代理商新增失败时，回滚用户新增的操作
		        
                Date date = new Date();
                agent.setCreateTime(date);
                agent.setUpdateTime(date);
                agent.setStatus(0);
                agent.setId(userId);//--这里为agent设置主键为user返回的id,代理商id和userId一样，业务要求
                agent.setAgentLevelId(levelId);//设置回原来的级别
                agentMapper.insert(agent);

                //新增代理商的余额账户默认给他余额设置为0  ph_user_balance
                agentMapper.addAgentBalance(agent);

                //添加代理商对应的图片
                if (imageList != null && imageList.size() != 0) {
                    for (AgentImage agentImage : imageList) {
                        agentImage.setCreateTime(date);
                        agentImage.setUpdateTime(date);
                        agentImage.setAgentId(agent.getId());
                    }
                }
                agentImageMapper.insertList(imageList);
            } else {
                result.setCode(userResult.getCode());
                result.setMessage(userResult.getMessage());
            }
        } catch (Exception e) {
        	//如果代理商新增失败了，删除用户
			 User userDelete = new User();
			 userDelete.setId(deleteUserId);
			iUserService.deleteUser(userDelete);
        	
            e.printStackTrace();
            logger.error("代理商新增异常:" + e.getMessage());
            result = getResult(ResultEnum.ADD_AGENT_EXCEPTION);
            throw new BizException("代理商新增异常:50001");
        }
        return result;
    }

    @Transactional(rollbackFor=Exception.class)
    public Result updateAgent(Agent agent, List<AgentImage> imageList)  throws BizException{

        //区域转换
        agent = transArea(agent);

        Result result = getResult(ResultEnum.SUCCESS);
        try {
            logger.debug("代理商修改");
            logger.debug("agent: " + new ObjectMapper().writeValueAsString(agent));
            logger.debug("imageList: " + new ObjectMapper().writeValueAsString(imageList));

            //获取添加的代理级别
            long levelId = agent.getAgentLevelId();

            //如果是市级代理去掉区
            long countyId = agent.getCountyId();
            if (1 == levelId) {
                agent.setCountyId(null);
            }

            //检查该区域该级别代理商是否修改成一经存在的代理,存在则不能修改
            AgentVo agentVo = agentMapper.getAgentByArea(agent);
            if(agentVo!=null){

                if (agentVo.getAgentLevelId() == agent.getAgentLevelId() && !agentVo.getId().equals(agent.getId())) {
                    return getResult(ResultEnum.ENTITY_AGENT_HAVE_EXCEPTION);
                }
            }

            //还原
            agent.setCountyId(countyId);

            //如该市/县已有县级/社区代理，审核通过后应自动关联上级代理商
            agent.setParentId(getSupperAgentByArea(agent).getId());

            //判断上级代理是否存在商户，如果存在则获取到新增代理下
            setMerchantBAgent(agent);

            //如该市/县已有县级/社区代理，审核通过后应自动关联下级代理商
            List<AgentVo> lowerLevelAgentVos = this.getLowerLevelAgentByArea(agent);
            if (lowerLevelAgentVos != null && lowerLevelAgentVos.size() != 0) {

                for (AgentVo lowerLevelAgentVo : lowerLevelAgentVos) {
                    Agent lowerLevelAgent = new Agent();
                    lowerLevelAgent.setId(lowerLevelAgentVo.getId());
                    lowerLevelAgent.setParentId(agent.getId());
                    logger.debug("市级代理，如该市已有县级/社区代理，审核通过时自动关联下级代理商");
                    agentMapper.updateByPrimaryKeySelective(lowerLevelAgent);
                }

            }

            agent.setAgentLevelId(levelId);//设置回原级别id
            Date date = new Date();
            agent.setUpdateTime(date);
            agentMapper.updateByPrimaryKeySelective(agent);

            //代理商图片
            if (imageList != null && imageList.size() != 0) {

                //设置删除已有的图片条件
                Example example = new Example(AgentImage.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("agentId", agent.getId());

                //删除已有的图片
                agentImageMapper.deleteByExample(example);

                for (AgentImage agentImage : imageList) {
                    agentImage.setCreateTime(date);
                    agentImage.setUpdateTime(date);
                    agentImage.setAgentId(agent.getId());
                }
                agentImageMapper.insertList(imageList);
            }

        } catch (Exception e) {
            logger.error("代理商修改异常:" + e.getMessage());
            result = getResult(ResultEnum.UPDATE_AGENT_EXCEPTION);
            throw new BizException("代理商修改异常:50002");
        }
        return result;

    }

    @Transactional(rollbackFor=Exception.class)
    public Result updateAgentStatus(Agent agent) throws BizException {

        Result result = getResult(ResultEnum.SUCCESS);
        try{
        	
            //1.冻结或者解冻账号
            if(3==agent.getStatus()||1==agent.getStatus()){
                User user = new User();
                user.setId(agent.getId());
                if(agent.getStatus()==3){
                    logger.debug("代理商冻结");
                    user.setIsable(Byte.decode(CommonConstants.USER_ISABLE_NO));

                    /**解除与商户的关系*/
                    //获取自己的商户列表
                    Merchant merchant = new Merchant();
                    merchant.setAgentId(agent.getId());
                    List<MerchantDetaileVo> merchantList = merchantMapper.getMerchantList(merchant);

                    if (merchantList != null && merchantList.size() != 0) {

                        //把商户归给上级代理
                        for (MerchantDetaileVo mer : merchantList) {
                            Merchant reMerchant = new Merchant();
                            reMerchant.setAgentId(getSupperAgentByArea(agent).getId());
                            reMerchant.setId(Long.valueOf(mer.getId()));
                            merchantMapper.updateByPrimaryKeySelective(reMerchant);
                        }
                    }

                }else{
                	
                	if(agent.getStatus()==1){

                        //如果是市级代理去掉区
                        long countyId = agent.getCountyId();
                        if (1 == agent.getAgentLevelId()) {
                            agent.setCountyId(null);
                        }


                        //解冻时或者审批通过时检查该区域该级别代理商是否存在,存在则不能审批
                        AgentVo agentVo = agentMapper.getAgentByArea(agent);
                        if(agentVo!=null){
                            if (agentVo.getAgentLevelId() == 3) {
                                return getResult(ResultEnum.ENTITY_COMMUNITY_HAVE_EXCEPTION);
                            } else {
                                return getResult(ResultEnum.ENTITY_AGENT_HAVE_EXCEPTION);
                            }
                        }
                        //还原
                        agent.setCountyId(countyId);

                        //如该市/县已有县级/社区代理，审核通过后应自动关联上级代理商
                        agent.setParentId(getSupperAgentByArea(agent).getId());

                        //如该市/县已有县级/社区代理，审核通过后应自动关联下级代理商
                        List<AgentVo> lowerLevelAgentVos = this.getLowerLevelAgentByArea(agent);
                        if (lowerLevelAgentVos != null && lowerLevelAgentVos.size() != 0) {

                            for (AgentVo lowerLevelAgentVo : lowerLevelAgentVos) {
                                Agent lowerLevelAgent = new Agent();
                                lowerLevelAgent.setId(lowerLevelAgentVo.getId());
                                lowerLevelAgent.setParentId(agent.getId());
                                logger.debug("市级代理，如该市已有县级/社区代理，审核通过时自动关联下级代理商");
                                agentMapper.updateByPrimaryKeySelective(lowerLevelAgent);
                            }

                    	}

                        //判断上级代理是否存在商户，如果存在则获取到新增代理下
                        setMerchantBAgent(agent);
                        
                        //解冻或者审批时更新密码并发送短信
                        //除了管理员类型的账号以外，需要随机生成密码
        	        	String pass = getSmsCode();
        	        	User userPass = new User();
        	        	userPass.setPassword(MD5.getMD5Str(pass));
        	        	userPass.setId(agent.getId());
        	        	iUserService.updatePassword(userPass);
                    	
                    	//通过短息的形式发送密码给用户
                        if (!sendMessage(agent.getPersonTel(), SmsCodeType.SEND_USER_PWD.getCodeType(), pass))
                        	throw new BizException("给用户发送密码短信接口异常:7071");
                	} 
                    logger.debug("代理商解冻");
                    user.setIsable(Byte.decode(CommonConstants.USER_ISABLE_YES));
                }
                iUserService.frozenOrEnableUser(user);
            }
            //2.设置代理商表状态
            agent.setUpdateTime(new Date());
            agentMapper.updateByPrimaryKeySelective(agent);

        } catch (Exception e) {
            e.printStackTrace();
            if(agent.getStatus()==3){
                logger.error("代理商冻结异常:" + e.getMessage());
                result = getResult(ResultEnum.CONGEALNO_AGENT_EXCEPTION);
                throw new BizException("代理商冻结异常:50016");
            }else{
                logger.error("代理商解冻异常:" + e.getMessage());
                result = getResult(ResultEnum.CONGEALYES_AGENT_EXCEPTION);
                throw new BizException("代理商解冻异常:50015");
            }
        }
        return result;

    }

    public Result deleteAgent(Agent agent) {
        agentMapper.deleteByPrimaryKey(agent);
        return getResult(ResultEnum.SUCCESS);
    }

    @Override
    public AgentVo getCityAgentByArea(Agent agent) {
        if (null == agent.getProvinceId() || 0 == agent.getProvinceId() || agent.getCityId() == null || 0 == (agent.getCityId())) {
            return null;
        } else {
            agent.setAgentLevelId(new Long(1));
            agent.setCountyId(null);
            agent.setTownId(null);
            AgentVo agentVo = agentMapper.getAgentByArea(agent);
            if (agentVo == null || "".equals(agentVo)) {
                return null;
            } else {
                return agentVo;
            }
        }

    }

    /**
     * 代理商获取上级代理
     *
     * @param agent
     * @return
     */
    public AgentVo getSupperAgentByArea(Agent agent) {
        //获取参数
        Agent agentNew = new Agent();
        agentNew.setAgentLevelId(agent.getAgentLevelId());
        agentNew.setProvinceId(agent.getProvinceId());
        agentNew.setCityId(agent.getCityId());
        agentNew.setCountyId(agent.getCountyId());
        agentNew.setTownId(agent.getTownId());

        //平台对象
        AgentVo agentVoP = new AgentVo();
        agentVoP.setAgentLevelId(new Long(0));
        agentVoP.setId(new Long(0));


        //获取添加的代理级别
        long levelId = agent.getAgentLevelId();
        AgentVo agentVo = new AgentVo();
        //根据代理级别查找上级代理
        if (levelId == 2) {
            agentNew.setAgentLevelId(new Long(1));
            agentNew.setCountyId(null);
            agentVo = agentMapper.getAgentByArea(agentNew);
            if (agentVo != null) {
                return agentVo;
            } else {
                return agentVoP;
            }
        } else if (levelId == 3) {
            agentNew.setTownId(null);
            agentNew.setAgentLevelId(new Long(2));
            agentVo = agentMapper.getAgentByArea(agentNew);
            if (agentVo != null) {
                return agentVo;
            } else {
                agentNew.setAgentLevelId(new Long(1));
                agentNew.setCountyId(null);
                agentVo = agentMapper.getAgentByArea(agentNew);
                if (agentVo != null) {
                    return agentVo;
                } else {
                    return agentVoP;
                }
            }
        } else {
            return agentVoP;
        }
    }


    /**
     * 商户获取上级代理
     * @param agent 代理商实体
     * @return
     */
    public AgentVo getAgentByArea(Agent agent) {
        Agent agentNew = new Agent();
        agentNew.setAgentLevelId(agent.getAgentLevelId());
        agentNew.setProvinceId(agent.getProvinceId());
        agentNew.setCityId(agent.getCityId());
        agentNew.setCountyId(agent.getCountyId());
        agentNew.setTownId(agent.getTownId());

        //获取添加的代理级别
        if( agent.getAgentLevelId()!=null){

            long levelId = agent.getAgentLevelId();

            //检查该区域该级别代理商是否存在
            AgentVo agentVo = agentMapper.getAgentByArea(agent);
            if (agentVo != null) {
                return agentVo;
            } else {
                //根据代理级别查找上级代理
                if (levelId == 2) {
                    agentNew.setAgentLevelId(new Long(1));
                    agentNew.setCountyId(null);
                    agentVo = agentMapper.getAgentByArea(agentNew);
                    if (agentVo != null) {
                        return agentVo;
                    } else {
                        AgentVo agentVoP = new AgentVo();
                        agentVoP.setAgentLevelId(new Long(0));
                        agentVoP.setId(new Long(0));
                        return agentVoP;
                    }
                } else if (levelId == 3) {
                    agentNew.setTownId(null);
                    agentNew.setAgentLevelId(new Long(2));
                    agentVo = agentMapper.getAgentByArea(agentNew);
                    if (agentVo != null) {
                        return agentVo;
                    } else {
                        agentNew.setAgentLevelId(new Long(1));
                        agentNew.setCountyId(null);
                        agentVo = agentMapper.getAgentByArea(agentNew);
                        if (agentVo != null) {
                            return agentVo;
                        } else {
                            AgentVo agentVoP = new AgentVo();
                            agentVoP.setAgentLevelId(new Long(0));
                            agentVoP.setId(new Long(0));
                            return agentVoP;
                        }
                    }
                } else {
                    AgentVo agentVoP = new AgentVo();
                    agentVoP.setAgentLevelId(new Long(0));
                    agentVoP.setId(new Long(0));
                    return agentVoP;
                }
            }
        } else {
            AgentVo agentVoP = new AgentVo();
            agentVoP.setAgentLevelId(new Long(0));
            agentVoP.setId(new Long(0));
            return agentVoP;
        }
    }

    /**
     * 获取下级代理
     * @param agent
     * @return
     */
    public List<AgentVo> getLowerLevelAgentByArea(Agent agent) {

    	Agent agentNew = new Agent();
    	agentNew.setAgentLevelId(agent.getAgentLevelId());
    	agentNew.setProvinceId(agent.getProvinceId());
    	agentNew.setCityId(agent.getCityId());
    	agentNew.setCountyId(agent.getCountyId());
        agentNew.setTownId(agent.getTownId());

        //获取代理级别
        long levelId = agent.getAgentLevelId();

        //检查该区域该级别代理商是否存在
        List<AgentVo> agentVos = new ArrayList<AgentVo>();

            if(levelId == 1){//市级代理
                agentNew.setTownId(null);
                agentNew.setCountyId(null);
                agentNew.setAgentLevelId(new Long(2));
                agentVos = agentMapper.getLowerAgent(agentNew);
                if (agentVos != null && agentVos.size() != 0) {
                    return agentVos;
                 } else {
                	 agentNew.setAgentLevelId(new Long(3));
                    agentVos = agentMapper.getLowerAgent(agentNew);
                    if (agentVos != null && agentVos.size() != 0) {
                        return agentVos;
                     } else {
                         return null;
                     }
                 }
            } else if(levelId == 2){//县级代理
                agentNew.setTownId(null);
                agentNew.setAgentLevelId(new Long(3));
                agentVos = agentMapper.getLowerAgent(agentNew);
                if (agentVos != null && agentVos.size() != 0) {
                    return agentVos;
                } else {
                    return null;
                }
            }else{
	                return null;
	        }
    }


    /**
     * 判断上级代理是否存在商户，如果存在则获取到新增代理下
     *
     * @param agent
     */
    public void setMerchantBAgent(Agent agent) {
        Merchant merchant = new Merchant();
        merchant.setAgentId(getSupperAgentByArea(agent).getId());
        merchant.setProvinceId(agent.getProvinceId());
        merchant.setCityId(agent.getCityId());
        merchant.setCountyId(agent.getCountyId());
        List<MerchantDetaileVo> merchantList = merchantMapper.getMerchantList(merchant);
        if (merchantList != null && merchantList.size() != 0) {
            if (3 == agent.getAgentLevelId()) {
                for (MerchantDetaileVo mer : merchantList) {
                    if (mer.getCountyId() != null) {
                        if (mer.getCountyId().toString().equals(agent.getCountyId().toString())) {
                            if (mer.getTownId() != null) {
                                String c1 = mer.getTownId().toString();
                                String c2 = agent.getTownId().toString();
                                if (c1.equals(c2)) {
                                    Merchant reMerchant = new Merchant();
                                    reMerchant.setAgentId(agent.getId());
                                    reMerchant.setId(Long.valueOf(mer.getId()));
                                    merchantMapper.updateByPrimaryKeySelective(reMerchant);
                                }
                            }
                        }
                    }
                }
            } else if (2 == agent.getAgentLevelId()) {
                for (MerchantDetaileVo mer : merchantList) {
                    if (mer.getCountyId() != null) {
                        String c1 = mer.getCountyId().toString();
                        String c2 = agent.getCountyId().toString();
                        if (c1.equals(c2)) {
                            Merchant reMerchant = new Merchant();
                            reMerchant.setAgentId(agent.getId());
                            reMerchant.setId(Long.valueOf(mer.getId()));
                            merchantMapper.updateByPrimaryKeySelective(reMerchant);
                        }
                    }
                }
            } else {
                for (MerchantDetaileVo mer : merchantList) {
                    Merchant reMerchant = new Merchant();
                    reMerchant.setAgentId(agent.getId());
                    reMerchant.setId(Long.valueOf(mer.getId()));
                    merchantMapper.updateByPrimaryKeySelective(reMerchant);
                }
            }
        }
    }

    /**
     * 根据所提交代理设置区域PositionId值
     *
     * @param agent
     */
    public void setPositionId(Agent agent) {
        Long levelId = agent.getAgentLevelId();
        if (3 == levelId) {
            agent.setPositionId(agent.getTownId());
        } else {
            agent.setPositionId(agent.getCountyId());
        }
    }


    /**
     * 根据所选区域Id重置转换省市区及社区Id
     *
     * @param agent
     * @return
     */
    public Agent transArea(Agent agent) {
        Long levelId = agent.getAgentLevelId();
        Long findAreaId = agent.getPositionId();
        Position position = iMerchantService.getPositionById(findAreaId);
        if (position != null && !"".equals(position)) {
            agent.setProvinceId(position.getProvinceId());
            agent.setCityId(position.getCityId());
            agent.setCountyId(position.getCountyId());
            if (3 == levelId) {
                agent.setTownId(position.getTownId());
            } else {
                agent.setTownId(null);
            }
        }
        return agent;
    }

  /**
   * 获取代理商的余额记录流水
	  * @return List<BalanceRecordVo> 商户余额记录集合
	  * @throws BizException
	  * @author liuy
   */
	@Override
	public Result getUserBalanceRecordVoList(@ModelAttribute PageBean page,@ModelAttribute  UserBalanceRecordVo userBalanceRecordVo) throws BizException {
		//备注：余额记录的来源有：充值、现金支付（线下订单）、供应链订单        线上积分支付、线下积分支付、线上订单（商户和代理商不涉及）
		
		PageHelper.startPage(page.getPageNum(), page.getPageSize());
		List<UserBalanceRecordVo> list=(Page<UserBalanceRecordVo>)agentMapper.getUserBalanceRecordVoList(userBalanceRecordVo);
	    PageInfo<UserBalanceRecordVo> pageInfo=new PageInfo<UserBalanceRecordVo>(list);
		return getResult(ResultEnum.SUCCESS,pageInfo.getList(),pageInfo.getTotal());
		
	}

    //发送短信接口
    private boolean sendMessage(String phone,String type,String message) {
    	logger.info("短信发送接口入参,phone={},type={}",phone,type);
    	Result result = smsCodeSendService.sendSmsCodeByCustomMsg(phone, type, message);
    	logger.info("短信发送接口返回值,result={}",JSON.toJSONString(result));
    	if (null != result && ResultEnum.SUCCESS.getCode().equals(result.getCode())) return true;
    	return false;
    }
    
	
    /**
     * 新增代理商充值记录
     * @param agentChargeRecord 代理商充值记录
     * @return Result
     * @author 刘颖
     */
	@Override
	public Result addAgentChargeRecord(AgentChargeRecord agentChargeRecord) throws Exception {
		this.agentChargeRecordMapper.addAgentChargeRecord(agentChargeRecord);
		return getResult(ResultEnum.SUCCESS);
	}

    /**
     * 新增代理商提现记录
     * @param agentDrawcashRecord 代理商提现记录
     * @return Result
     * @author 刘颖
     */
	@Override
	public Result addAgentDrawcashRecord(AgentDrawcashRecord agentDrawcashRecord) throws Exception {
		this.agentDrawcashRecordMapper.addAgentDrawcashRecord(agentDrawcashRecord);
		return  getResult(ResultEnum.SUCCESS);
	}
	
	/**
     * 查询登陆人当天的已提现总额
     * @param agentDrawcashRecord 代理商提现记录
     * @return Result
     * @author 刘颖
     */
	@Override
	public BigDecimal getDrawcashMoneyToday(AgentDrawcashRecord agentDrawcashRecord) throws Exception {
		return this.agentDrawcashRecordMapper.getDrawcashMoneyToday(agentDrawcashRecord);
	}
	
	/**
     * 查询登陆人提现待审核记录
     * @param agentDrawcashRecord 代理商提现记录
     * @return Result
     * @author 刘颖
     */
	@Override
	public BigDecimal getDrawcashStatusPendingTotal(AgentDrawcashRecord agentDrawcashRecord) throws Exception {
		return this.agentDrawcashRecordMapper.getDrawcashStatusPendingTotal(agentDrawcashRecord);
	}
}
